import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
from os import path
from wordcloud import WordCloud
from PIL import Image
import jieba
from matplotlib import font_manager as fm
from matplotlib import cm
from sklearn import preprocessing
from mpl_toolkits.mplot3d.axes3d import Axes3D

# plt.rcParams['axes.unicode_minus'] = False
"""
# 散点
plt.plot([1, 2, 3, 4, 5], [2, 5, 8, 12, 19], 'ro')
"""

"""
# 折线图
x = range(1, 15, 1)
y = range(1, 42, 3)
plt.plot(x, y)
fig = plt.figure(figsize=(5, 3), facecolor='pink')
plt.plot([1, 2, 3, 4, 5])  # 直线
"""

"""
#体温折线
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['xtick.direction'] = 'in'
plt.rcParams['ytick.direction'] = 'in'
df = pd.read_excel('../data3/data任务程序/体温.xls')
x = df['日期']
y = df['体温']
plt.plot(x, y, color='m', linestyle='-', marker='o', mfc='w')
plt.grid(color='0.5', linestyle='--', linewidth=1)
for a, b in zip(x, y):
    plt.text(a, b + 0.05, '%.1f' % b, ha='center', va='bottom', fontsize=9)
plt.legend(("基础体温",), loc="upper right", fontsize=10)
plt.annotate('最高体温', xy=(9, 37.1), xytext=(10.5, 37.1),
             xycoords='data3', arrowprops=dict(facecolor='r', shrink=0.05))
dates = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14']
plt.xticks(range(1, 15, 1), dates)
plt.tick_params(bottom=False, left=True, right=False, top=True)
plt.subplots_adjust(left=0.2, right=0.9, top=0.9, bottom=0.2)
plt.xlabel("2020年2月")
plt.ylabel("基础温度")
plt.show()
"""

"""
# 曲线
data3 = np.arange(0, 1.1, 0.01)
plt.title('lines')
plt.xlabel("x")
plt.xlabel("y")
plt.xlim((0, 1))
plt.ylim((0, 1))
plt.xticks([0, 0.2, 0.4, 0.6, 0.8, 1])
plt.yticks([0, 0.2, 0.4, 0.6, 0.8, 1])
plt.plot(data3, data3 ** 2)
plt.plot(data3, data3 ** 4)
plt.legend(['y=x^2', 'y=x^4'])
plt.show()
"""

"""
df1 = pd.read_excel("../data3/data任务程序/data.xls")
x1 = df1["姓名"]
y1 = df1["语文"]
y2 = df1["数学"]
y3 = df1["英语"]

plt.rcParams["font.sans-serif"] = ["SimHei"]
plt.rcParams["xtick.direction"] = "out"
plt.rcParams["ytick.direction"] = "in"
plt.title("语数英成绩大比拼", fontsize='18')
plt.plot(x1, y1, label="语文", color="r", marker="p")
plt.plot(x1, y2, label="数学", color="g", marker=".", mfc="r", ms=8, alpha=0.7)
plt.plot(x1, y3, label="英语", color="b", linestyle="-.", marker="*")
plt.grid(axis="y")

plt.ylabel("分数")

plt.yticks(range(50, 150, 10))
plt.legend(["语文", "数学", "英语"])
"""

"""
data = np.load("../data3/data任务程序/国民经济核算季度数据.npz", allow_pickle=True)
name = data["columns"]
values = data["values"]
p = plt.figure(figsize=(12, 12))

ax5 = p.add_subplot(2, 1, 1)
plt.scatter(values[:, 0], values[:, 3], marker="o", c="r")
plt.scatter(values[:, 0], values[:, 4], marker="D", c="b")
plt.scatter(values[:, 0], values[:, 5], marker="v", c="y")
plt.ylabel("生产总值(亿元)")
plt.title("2000-2017年")
plt.legend(["第一产业", "第二产业", "第三产业"])

ax6 = p.add_subplot(2, 1, 2)
plt.scatter(values[:, 0], values[:, 6], marker="o", c="r")
plt.scatter(values[:, 0], values[:, 7], marker="D", c="b")
plt.scatter(values[:, 0], values[:, 8], marker="v", c="y")
plt.scatter(values[:, 0], values[:, 9], marker="8", c="g")
plt.scatter(values[:, 0], values[:, 10], marker="p", c="c")
plt.scatter(values[:, 0], values[:, 11], marker="+", c="m")
plt.scatter(values[:, 0], values[:, 12], marker="s", c="k")
plt.scatter(values[:, 0], values[:, 13], marker="*", c="purple")
plt.scatter(values[:, 0], values[:, 14], marker="d", c="brown")

plt.legend(["农业", "工业", "建筑", "批发", "交通", "餐饮", "金融", "房地产", "其他"])

plt.xlabel("年份")
plt.ylabel("生产总值")
plt.xticks(range(0, 70, 4), values[range(0, 70, 4), 1], rotation=45)
"""

"""
# 单柱形图
df = pd.read_excel("../data3/data任务程序/books.xlsx")
plt.rcParams["font.sans-serif"] = ["SimHei"]
x = df["年份"]
height = df["销售额"]
plt.grid(axis="y", which="major")
plt.xlabel("年份")
plt.ylabel("线上销售额（元）")
plt.title("2013-2019年线上图书馆销售额分析图")
plt.bar(x, height, width=0.5, align="center", color="b", alpha=0.5)
for a, b in zip(x, height):
    plt.text(a, b, format(b, ","), ha="center", va="bottom", fontsize=9, color="b", alpha=0.9)
plt.legend(["销售额"])
plt.show()
"""

"""
# 多柱形图
df = pd.read_excel("../data3/data任务程序/books.xlsx", sheet_name="Sheet2")
plt.rcParams["font.sans-serif"] = ["SimHei"]
plt.rcParams['axes.unicode_minus']=False
x = df["年份"]
y1 = df["京东"]
y2 = df["天猫"]
y3 = df["自营"]
width = 0.25
plt.ylabel("线上销售额（元）")
plt.title("2013-2019年线上图书馆销售额分析图")
plt.bar(x, y1, width=width, color="darkorange")
plt.bar(x + width, y2, width=width, color="deepskyblue")
plt.bar(x + 2 * width, y3, width=width, color="g")
for a, b in zip(x, y1):
    plt.text(a, b, format(b, ","), ha="center", va="bottom",
             fontsize=8)
for a, b in zip(x, y2):
    plt.text(a + width, b, format(b, ","), ha="center", va="bottom",
             fontsize=8)
for a, b in zip(x, y3):
    plt.text(a + 2 * width, b, format(b, ","), ha="center", va="bottom",
             fontsize=8)
plt.legend(["京东", "天猫", "自营"])
plt.show()
"""
"""
# 饼图
plt.rcParams["font.sans-serif"] = ["SimHei"]
data3 = np.load("../data3/data任务程序/国民经济核算季度数据.npz", allow_pickle=True)
name = data3["columns"]
values = data3["values"]
plt.figure(figsize=(6, 6))
label = ["第一产业", "第二产业", "第三产业"]
explode = [0.1, 0.01, 0.01]
plt.pie(values[-1, 3:6], explode=explode, labels=label,
        autopct="%1.1f%%", pctdistance=0.7)
plt.title("2017年第一季度各产业国民生产总值饼图")
plt.show()
"""

"""
# 多个饼图
df = pd.read_excel("../data3/data任务程序/data2.xls")
plt.rcParams["font.sans-serif"] = ["SimHei"]
plt.figure(figsize=(5, 3))
labels = df["省"]
sizes = df["销量"]
color = ["red", "yellow", "slateblue", "green", "magenta", "cyan", "darkorange",
         "lawngreen", "pink", "gold"]
plt.pie(sizes, labels=labels, colors=color, labeldistance=1.2, autopct="%1.1f"
        , startangle=90, center=(0.2, 0.2), textprops={"fontsize": 9, "color": "k"},
        pctdistance=0.6)
plt.axis("equal")
plt.title("2020年1月各省销量占比 情况分析")
"""

"""
# 内嵌环形图
plt.rcParams["font.sans-serif"] = ["SimHei"]
df1 = pd.read_excel("../data3/data任务程序/data2.xls")
df2 = pd.read_excel("../data3/data任务程序/data2.xls", sheet_name="2月")
x1 = df1["销量"]
x2 = df2["销量"]
colors = ["red", "yellow", "slateblue", "green", "magenta", "cyan", "darkorange",
          "lawngreen", "pink", "gold"]
plt.pie(x1, colors=colors, autopct="%.1f%%"
        , radius=1, center=(0.2, 0.2), pctdistance=0.85,
        wedgeprops=dict(linewidth=2, width=0.3, edgecolor="w"))
plt.pie(x2, colors=colors, autopct="%.1f%%"
        , radius=0.7, center=(0.2, 0.2), pctdistance=0.7,
        wedgeprops=dict(linewidth=2, width=0.4, edgecolor="w"))
legend_text = df1["省"]
plt.legend(legend_text, title="地区", frameon=False, bbox_to_anchor=(0.2, 0.5))
plt.axis("equal")
plt.title("2020年1月2月各省销量占比 情况分析")
plt.show()
"""

"""
# 箱线图
x1 = [1, 2, 3, 5, 7, 9]
x2 = [10, 22, 13, 15, 8, 19]
x3 = [18, 31, 18, 19, 14, 25]
plt.boxplot([x1, x2, x3])
plt.show()
"""

"""
# 通过箱形图查找客人总消费的数据中存在的异常值
df = pd.read_excel("../data3/data任务程序/tips.xlsx")
plt.boxplot(x=df["总消费"],
            whis=1.5,
            widths=0.3,
            patch_artist=True,
            showmeans=True,
            boxprops={"facecolor": "RoyalBlue"},
            flierprops={"markerfacecolor": "red", "markeredgecolor": "red", "markersize": 3},
            meanprops={"marker": "h", "markerfacecolor": "black", "markersize": 8},
            medianprops={"linestyle": "--", "color": "orange"},
            labels=[""])
plt.show()
Q1 = df["总消费"].quantile(q=0.25)
Q3 = df["总消费"].quantile(q=0.75)
low_limit = Q1 - 1.5 * (Q3 - Q1)
up_limit = Q3 + 1.5 * (Q3 - Q1)
val = df["总消费"][(df["总消费"] > up_limit) | (df["总消费"] < low_limit)]
print("异常值如下:")
print(val)
"""

"""
# 2000-2017年各产业国民生产总值箱线图
plt.rcParams["font.sans-serif"] = ["SimHei"]
data3 = np.load("../data3/data任务程序/国民经济核算季度数据.npz", allow_pickle=True)
name = data3["columns"]
values = data3["values"]
label = ["第一产业", "第二产业", "第三产业"]
gdp = (list(values[:, 3]), list(values[:, 4]), list(values[:, 5]))
plt.figure(figsize=(6, 4))
plt.boxplot(gdp, notch=True, labels=label, meanline=True)
plt.title("2000-2017年各产业国民生产总值箱线图")
plt.show()
"""

"""
#面积图
x = [1, 2, 3, 4, 5]
y1 = [6, 9, 5, 8, 4]
y2 = [3, 2, 5, 4, 3]
y3 = [8, 7, 8, 4, 3]
y4 = [7, 4, 6, 7, 12]
plt.stackplot(x, y1, y2, y3, y4, colors=['g', 'c', 'r', 'b'])
"""
"""
#标准面积图
df = pd.read_excel("../data3/data任务程序/books.xlsx")
plt.rcParams['font.sans-serif'] = ['SimHei']

x = df['年份']
y = df['销售额']
plt.title("2013-2019线上图书销售情况")
plt.stackplot(x, y)
"""

"""
# 堆叠面积图
# df = pd.read_excel("../data3/data任务程序/books.xlsx")
plt.rcParams['font.sans-serif'] = ['SimHei']

x = df['年份']
y1 = df['京东']
y2 = df['天猫']
y3 = df['自营']
plt.stackplot(x, y1, y2, y3, colors=['g', 'b', 'p', 'r'])

plt.legend(['京东', '天猫', '自营'], loc='upper left')
"""

"""
#热力图
X = [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]]
plt.imshow(X)
"""
"""
# 学生成绩统计热力图
df = pd.read_excel("../data3/data任务程序/data1.xls", sheet_name="高二一班")
plt.rcParams['font.sans-serif'] = ['SimHei']
X = df.loc[:, "语文":"生物"].values
name = df["姓名"]
plt.imshow(X)
plt.xticks(range(0, 6, 1), ["语文", "数学", "英语", "物理", "化学", "生物"])
plt.yticks(range(0, 12, 1), name)
plt.colorbar()
plt.title("学生成绩统计热力图")
"""

"""
fig = plt.figure()
axes3d = Axes3D(fig)
zs = [1, 5, 10, 15, 20]
for z in zs:
    x = np.arange(0, 10)
    y = np.random.randint(0, 30, size=10)
    axes3d.bar(x, y, zs=z, zdir="x", color=["r", "green", "yellow", "c"])
"""
"""
# 多层折线图
x = [1, 2, 3, 4, 5]
y1 = [6, 9, 5, 8, 4]
y2 = [3, 2, 5, 4, 3]
y3 = [8, 7, 8, 4, 3]
y4 = [7, 4, 6, 7, 12]
plt.stackplot(x, y1, y2, y3, y4, colors=['g', 'c', 'r', 'b'])
plt.show()
"""
"""
# 雷达图
courses0 = ['C++', 'Python', 'java', 'C', 'C#', 'Go', 'Matlab']
courses = ['C++', 'Python', 'java', 'C', 'C#', 'Go', 'Matlab']
scores = [82, 100, 90, 78, 40, 66, 88]
datalength = len(scores)
angles0 = np.linspace(0, 2 * np.pi, datalength, endpoint=False)  # 均分圾坐标
angles = np.linspace(0, 2 * np.pi, datalength, endpoint=False)  # 均分极坐标

scores.append(scores[0])  # 在末尾添加第一个值，保证曲线闭合
angles = np.append(angles, angles[0])
plt.polar(angles, scores, 'rv-', lw=2)
plt.thetagrids(angles0 * 180 / np.pi, courses0, fontproperties=' simhei')
plt.fill(angles, scores, facecolor='r', alpha=0.4)
plt.ylim(0, 100)
plt.show()
"""

# Seaborn概述

"""
# 绘制简单的柱形图
plt.figure(figsize=(4, 3))
x = [1, 2, 3, 4, 5]
y = [10, 20, 30, 40, 50]
plt.bar(x, y)
plt.show()
sns.set_style("darkgrid")
sns.barplot(x, y)
plt.show()
"""

"""
# 折线图 relplot
sns.set_style("darkgrid")
plt.rcParams['font.sans-serif'] = ['SimHei']
df1 = pd.read_excel("../data3/data附加知识/data.xls")
sns.relplot(x="学号", y="语文", kind="line", data=df1)
plt.show()
"""

"""
# 折线图 lineplot
sns.set_style("darkgrid")
plt.rcParams['font.sans-serif'] = ['SimHei']
df1 = pd.read_excel("../data3/data附加知识/data.xls")
sns.lineplot(x="学号", y="语文", data=df1)
plt.show()
"""

"""
# 多折线图
sns.set_style("darkgrid")
plt.rcParams['font.sans-serif'] = ['SimHei']
df1 = pd.read_excel("../data3/data附加知识/data.xls")
dfs = [df1["语文"], df1["数学"], df1["英语"]]
sns.lineplot(data=dfs
plt.show()
"""

"""
# 简单直方图
sns.set_style('darkgrid')
plt.rcParams['font.sans-serif'] = ['simHei']  # 解决中文乱码
df1 = pd.read_excel("../data3/data附加知识/data2.xls")  # 导入Excel文件
input = df1[['得分']]
sns.distplot(input, rug=True)  # 直方图，显示观测的小细条
plt.show()  # 显示
"""

"""
# 多柱形图
sns.set_style('darkgrid')
plt.rcParams['font.sans-serif'] = ['simHei']  # 解决中文乱码
df1 = pd.read_excel('../data3/data附加知识/data.xls',
                    sheet_name='sheet2')  # 导入Excel文件
sns.barplot(x="学号", y="得分", hue="学科", data=df1)  # 条形图
plt.show()  # 显示
"""

"""
# 散点图
sns.set_style('darkgrid')
# 读取数据tips
tips = pd.read_csv("../data3/data附加知识/tips.csv")
sns.relplot(x="total_bill", y="tip", data=tips, color='r')
plt.show()  # 显示
"""

"""
# 回归直线
sns.set_style("darkgrid")  # 读数据对象tips
tips = pd.read_csv("../data3/data附加知识/tips.csv")  # 绘制回归图形
sns.lmplot(x='total_bill', y="tip", data=tips)
plt.show()  # 显示
"""

"""
# 箱线图
sns.set_style('darkgrid')  # 读款数据象tip5
tips = pd.read_csv('../data3/data附加知识/tips.csv')  # 绘制箱形图
sns.boxplot(x="day", y="total_bill", hue="time", data=tips)
plt.show()  # 显示图形

"""

"""
# 给制多个变量的核密度图
sns.set_style('darkgrid')
df = pd.read_csv("../data3/data附加知识/iris.csv")  # 读取数据
df.head()
p1 = sns.kdeplot(df['sepal_width'], shade=True, color="r")
p1 = sns.kdeplot(df['sepal_length'], shade=True, color="b")
plt.show()
"""

"""
# 边际核密度图
sns.set_style('darkgrid')
df = pd.read_csv("../data3/data附加知识/iris.csv")  # 读取数据
df.head()
sns.jointplot(x=df["sepal_length"], y=df["sepal_width"], kind="kde", space=0)
plt.show()
"""

"""
# 提琴图
tips = pd.read_csv("../data3/data附加知识/tips.csv")
sns.violinplot(x='total_bill', y="day", hue="time", data=tips)
plt.show()
"""

"""
# 双Y轴可视化数据分析图表
df = pd.read_excel("../data3/data附加知识/mrbook.xlsx")  # 导入Excel文件
x = [1, 2, 3, 4, 5, 6]
y1 = df['销量']
y2 = df['rate']
fig = plt.figure()
plt.rcParams['font.sans-serif'] = ['simHei']  # 解决中文乱码
ax1 = fig.add_subplot(111)  # 添加子图
plt.title("销量情况对比")  # 图表标题
# 图表x轴标题
plt.xticks(x, ['1月', '2月', "3月", '4月', '5月', '6月'])
ax1.bar(x, y1, label='left')
ax1.set_ylabel('销量(册)')  # y轴标签
ax2 = ax1.twinx()  # 共享x轴，添加一条v轴坐标轴
ax2.plot(x, y2, color='black', linestyle='--',
         marker='o', linewidth=2, label=u"增长率")
ax2.set_ylabel(u"增长率")
for a, b in zip(x, y2):
    plt.text(a, b + 0.02, '%.2f' % b, ha='center',
             va='bottom', fontsize=10, color='red')
plt.show()
"""

"""
# 堆叠柱形图可视化数据分析图变
sns.set_style("darkgrid")
file = "../data3/data附加知识/mrtb_data.xlsx"
df = pd.DataFrame(pd.read_excel(file))
plt.rc('font', family='SimHei', size=13)
# 通过resetindex0函散牌groupby0的分组结架质新没置卖引
df1 = df.groupby(["类别"])["买家实际支付金额"].sum()
df2 = df.groupby(["类别", "性别"])["买家会员名"].count().reset_index()
men_df = df2[df2["性别"] == '男']
women_df = df2[df2["性别"] == "女"]
men_list = list(men_df["买家会员名"])
women_list = list(women_df["买家会员名"])
nun = np.array(list(df1))  # 消费金额
# #计算男性用户比例
ratio = np.array(men_list) / (np.array(men_list) + np.array(women_list))
np.set_printoptions(precision=2)  # 使用setprintoptions没置输出的错度#没管男生女生消费金额
men = nun * ratio
women = nun * (1 - ratio)
df3 = df2.drop_duplicates(["类别"])  # 去除类别重复的记录
name = (list(df3["类别"]))
# #生成图赛
x = name
width = 0.5
idx = np.arange(len(x))
plt.bar(idx, men, width, color="slateblue", label="男性用户")
plt.bar(idx, women, width, bottom=men, color="orange", label="女性用户")
plt.xlabel("消费类别")
plt.ylabel('男女分布')
plt.xticks(idx + width / 2, x, rotation=20)  # 在图表上显示数字
for a, b in zip(idx, men):
    plt.text(a, b, "%.0f" % b, ha='center', va='top',
             fontsize=12)  # 对齐方式'top', 'botton', 'center', 'baseline', 'center baseline
for a, b, c in zip(idx, women, men):
    plt.text(a, b + c + 0.5, "%.0f" % b, ha='center', va="bottom", fontsize=12)
plt.legend()
plt.show()
"""

"""
# 颜色渐变饼图
plt.rcParams['font.sans-serif'] = ['simHei']  # 解决中文乱码
plt.style.use('ggplot')

# 原始数据
shapes = ['天津，"江西省"，"安徽省', '云南省', '福建省', "河南省", "辽宁省",
          "重庆", "湖南省", "四川省", "北京", "上海", "广西壮族自治区",
          "河北省", "浙江省", "江苏省", "湖北省", "山东省", '广东省']
values = [287, 383, 842, 866, 1187, 1405, 1495, 1620, 1717,
          2313, 2378, 3070, 4332, 5841,
          6482, 7785, 9358]
s = pd.Series(values, index=shapes)
labels = s.index
sizes = s.values
fig, ax = plt.subplots(figsize=(6, 6))  # 设置绘图的区域大小
colors = cm.rainbow(np.arange(len(sizes)) / len(sizes))  # 颜色地图:秋天→彩虹→灰色→春天→黑色
patches, texts, autotexts = ax.pie(sizes, labels=labels, autopct="%1.1f",
                                   shadow=False, startangle=170, colors=colors)
ax.axis('equal')
ax.set_title('各省线上图书销售占比图', loc="left")
# 重新设置字体大小
proptease = fm.FontProperties()
# 字体大小(从小到大):xx-small、x-small、small、medium、large、x-large、xx-large，或者是数字，如18 proptease.set_size('small')
plt.setp(autotexts, fontproperties=proptease)
plt.setp(texts, fontproperties=proptease)
plt.show()
"""

"""
# 等高线
# 计算x，y坐标对应的高度值
def f(x, y):
    return (1 - x / 2 + x ** 5 + y ** 3) * np.exp(-x ** 2 - y ** 2)


# 生成x，y的数据
n = 256
x = np.linspace(-3, 3, n)
y = np.linspace(-3, 3, n)
# 把x，y数据转换为二维数据
X, Y = np.meshgrid(x, y)  # 填充等高线
plt.contourf(X, Y, f(X, Y))
# 显示图表
plt.show()
"""

"""
# 统计双色球中中奖热力图
sns.set()  # 使用默认设置
plt.figure(figsize=(6, 6))
plt.rcParams['font.sans-serif'] = ['simHei']  # 显示中文
df = pd.read_csv('../data3/data附加知识/input-双色球.csv', encoding='gb2312')  # 导入Excel文件
series = df['中奖号码'].str.split(' ', expand=True)  # 提取每一位的中奖号码
# 对每一位的中奖号码统计出现次数
df1 = df.groupby(series[0]).size()
df2 = df.groupby(series[1]).size()
df3 = df.groupby(series[2]).size()
df4 = df.groupby(series[3]).size()
df5 = df.groupby(series[4]).size()
df6 = df.groupby(series[5]).size()
df7 = df.groupby(series[6]).size()
# 横向表合并(行对齐)
input = pd.concat([df1, df2, df3, df4, df5, df6, df7], axis=1, sort=True)
input = input.fillna(0)  # 空值NaN替换为0
input = input.round(0).astype(int)  # 浮点数转换为整数
plt.title('统计2014~2019年双色球中奖数字热力图')
sns.heatmap(input, annot=True, fmt='d', lw=0.5)  # 绘制热力图
plt.xlabel('中奖号码位数')
plt.ylabel('双色球数字')
x = ['第1位', "第2位", '第3位', '第4位', "第5位", "第6位", "第7位"]
plt.xticks(range(0, 7, 1), x, ha='left')
plt.show()
"""

"""
# 生成普通的wordcloud
text = open(path.join("../data3/data词云&空间信息展示/data/sandstorm.txt"), encoding="utf8").read()
font_path = path.join("../data3/data词云&空间信息展示/font/VINERITC.TTF")
wordcloud = WordCloud(font_path=font_path,
                      max_font_size=200,
                      min_font_size=5,
                      random_state=10,
                      max_words=300,
                      margin=1, width=1000, height=700,
                      background_color="white").generate(text)

wordcloud.to_file("wordcloud.jpg")
plt.figure(dpi=150)
plt.imshow(wordcloud)
plt.axis("off")
plt.show()
"""

"""
text = open(path.join("../data3/data词云&空间信息展示/data/sandstorm.txt"), encoding="utf8").read()
font_path = path.join("../data3/data词云&空间信息展示/font/VINERITC.TTF")
mask = np.array(Image.open(path.join("../data3/data词云&空间信息展示/data/image01.jpg")))
wordcloud = WordCloud(font_path=font_path,
                      mask=mask,
                      margin=1,
                      random_state=1,
                      background_color="white").generate(text)
wordcloud.to_file("wordcloud_mask.jpg")
plt.figure(dpi=150)
plt.imshow(wordcloud)
plt.axis("off")
plt.show()
"""

"""
#对句子进行分词
def seg_sentence(sentence):
    sentence_seged=jieba.cut(sentence.strip())
    outstr=""
    for word in sentence_seged:
        if word!='\t':
            outstr+=word
            outstr+=" "
     return outstr.strip()

seg_sentence("欢迎大家来学习数据分析与可视化课程")
"""

"""
#创建停用词list
def stopwordslist(filepath):
    stopwords=[line.strip() for line in open(filepath,"r",encoding="utf-8").readlines()]
    return stopwords
stopwordslist("./cn_stopwords.txt")
"""

"""
#中文句子分词与停用词混用
def seg_sentence(sentence):
    sentence_seged=jieba.cut(sentence.strip())
    stopwords=stopwordslist("./stop.txt")
    outstr=""
    for word in sentence_seged:
        if word not in stopwords:
            if word!='\t':
                outstr+=word
                outstr+=" "
     return outstr

"""


def seg_sentence(sentence):
    sentence_seged = jieba.cut(sentence.strip())
    outstr = ""
    for word in sentence_seged:
        if word != '\t':
            outstr += word
            outstr += " "
    return outstr.strip()


def stopwordslist(filepath):
    stopwords = [line.strip() for line in open(filepath, "r", encoding="utf-8").readlines()]
    return stopwords


"""
# 生成词云
inputs = open("../data3/data词云&空间信息展示/data/henu.txt", "r", encoding="utf-8")
outputs = open("../data3/data词云&空间信息展示/data/output.txt", "w", encoding="utf-8")
for line in inputs:
    line_seg = seg_sentence(line)
    outputs.write(line_seg + "\n")
outputs.close()
inputs.close()

mask = np.array(Image.open("../data3/data词云&空间信息展示/data/mask.jpg"))
inputs = open("../data3/data词云&空间信息展示/data/output.txt", "r", encoding="utf-8")
mytext = inputs.read()
wordcloud = WordCloud(mask=mask,
                      width=3000,
                      height=3000,
                      background_color="white",
                      margin=1,
                      max_words=300,
                      min_font_size=10,
                      max_font_size=None,
                      repeat=False,
                      font_path="../data3/data词云&空间信息展示/font/FZKaTong-M19S.ttf"
                      ).generate(mytext)
wordcloud.to_file("../data3/data词云&空间信息展示/tmp/wordcloud.jpg")
inputs.close()
plt.figure(dpi=150)
plt.imshow(wordcloud)
plt.axis("off")
plt.show()
"""

"""
# 词云与原图融合
inputs = open("../data3/data词云&空间信息展示/data/henu.txt", "r", encoding="utf-8")
outputs = open("../data3/data词云&空间信息展示/data/output.txt", "w", encoding="utf-8")
for line in inputs:
    line_seg = seg_sentence(line)
    outputs.write(line_seg + "\n")
outputs.close()
inputs.close()
mask = np.array(Image.open("../data3/data词云&空间信息展示/data/mask.jpg"))
inputs = open("../data3/data词云&空间信息展示/data/output.txt", "r", encoding="utf-8")
mytext = inputs.read()
wordcloud = WordCloud(mask=mask,
                      width=3000,
                      height=3000,
                      background_color="white",
                      margin=1,
                      colormap="inferno",
                      mode="RGBA",
                      max_words=300,
                      min_font_size=10,
                      max_font_size=None,
                      repeat=False,
                      font_path="../data3/data词云&空间信息展示/font/FZKaTong-M19S.ttf"
                      ).generate(mytext)
wordcloud.to_file("../data3/data词云&空间信息展示/tmp/wordcloud-to.png")
inputs.close()
# 词云与原图融合
img = Image.open("../data3/data词云&空间信息展示/tmp/wordcloud-to.png")
background = Image.open("../data3/data词云&空间信息展示/data/mask.jpg")
background = background.convert("RGBA")
img = Image.blend(background, img, 0.7)
img.save("../data3/data词云&空间信息展示/tmp/wordcloud-together.png")
plt.figure(dpi=150)
plt.imshow(wordcloud)
plt.axis("off")
plt.show()
"""

"""
#图像处理
from scipy.ndimage import gaussian_gradient_magnitude
img=Image.open("./parrot-by-jose-mari-gimenez2.jpg")
mask_color=np.array(img)
mask_color=mask_color[::3,::3]
mask_image=mask_color.copy()
mask_image[mask_image.sum(axis=2)==0]=255
edges=np.mean([gaussian_gradient_magnitude(mask_color[:,:,i]/255.,2)for i in range(3)],axis=0)
mask_image[edges>.08]=255
im=Image.fromarray(mask_image)
im.save("./parrot-change.jpg")
inputs=open("./output.txt","r",encoding="utf-8")
mytext=inputs.read()
wordcloud=WordCloud(mask=mask_image,
                    relative_scaling=0,
                    collocations=False,
                    mode="RGB",
                    margin=1,
                    max_words=10000,
                    min_font_size=10,
                    max_font_size=None,
                    repeat=True,
                    font_path="./FXKaTong-M19S.ttf"
                    ).generate(mytext)
wordcloud.to_file("wordcloud-parrot2.jpg")
inputs.close()
image_colors=ImageColorGenerator(mask_color)

wordcloud.recolor(color_func=image_colors)
wordcloud.to_file("wordcloud-parrot2.jpg")
inputs.close()
plt.figure(dpi=150)
plt.imshow(wordcloud)
plt.axis("off")
plt.show()
"""
"""
world_map = folium.Map()
world_map.save("../mapHtml/pic1.html")
"""

"""
河大地图
latitude = 34.818951
longitude = 114.309158
kf_map = folium.Map(
    location=[latitude, longitude],
    zoom_start=15,
    tiles="http://webrd01.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=7&x={x}&y={y}&z={z}",
    attr="default"
)
kf_map.save("../mapHtml/pic2.html")
"""
# plt.show()
arr2 = np.array([1, 2, 3])
print(arr2.shape)
